import Utils from "../utils/Utils.ts";

const {prefixName, assign, defaultTo} = Utils;

class UImage implements UComponent {

    get name(): string {
        return this.options.name
    }

    get zIndex(): number {
        return this.options.zIndex
    }

    visible: boolean = true

    options: Required<UComponent.UImageOption> = {
        x: 0,
        y: 0,
        width: 40,
        height: 80,
        src: '',
        zIndex: 1,
        name: prefixName('u_image')
    }

    constructor(uImageOption: UComponent.UImageOption) {
        this.setOption(uImageOption)
    }

    draw(ctx: CanvasRenderingContext2D): void {
        const {x, y, src, width, height} = this.options
        ctx.save()
        const img = new Image()
        img.src = src

        img.onload = function () {
            ctx.drawImage(img, x, y, width, height)
            ctx.restore()
        }

        img.onerror = function () {
            console.log('图片加载失败')
            ctx.restore()
        }
    }

    setOption(option?: Partial<UComponent.UImageOption>): void {
        this.options = assign(this.options, defaultTo(option, {})) as Required<UComponent.UImageOption>
    }
}

export default UImage

